package br.unifor.cct.mia.util;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;

public class SaveReportFS {
	private BufferedWriter writer;
	private File file;
	
	public SaveReportFS(String name, double[] data, String struc) throws IOException{	    
		file = new File(name);
		writer = new BufferedWriter(new FileWriter(file));
				
		createRelationStructure(struc,"struc",data);
	}
		
	public void createRelationStructure(String strucFile, String name, double[] data) throws IOException {
		
		addLine("@relation "+name+"\n\n");
		
		FileInputStream fIn;
		try {
			fIn = new FileInputStream(strucFile);
			BufferedReader reader = new BufferedReader(new InputStreamReader(fIn));
			
			int var = 0;
			String line = reader.readLine();
			while ( var < data.length+1 ) {
				
				if ( var < data.length && data[var] == 0 ) {
					var++;
					line = reader.readLine();
					continue;
				}
				
				if ( line == null ) {
					continue;
				}
				
				String[] tokens = line.split(" ");
				
				String atribute = "@attribute ";
				String attName = tokens[0];
				String attType = tokens[1];
				
				atribute += attName+" ";
				if ( "discrete".equalsIgnoreCase(attType) ) {
					atribute += "{";
					for ( int i=2; i<tokens.length; i++ ) {
						atribute += tokens[i];
						if ( i+1 != tokens.length ) {
							atribute += ",";
						}
					}
					atribute += "}\n";
				} else if ( "continuous".equalsIgnoreCase(attType) ) {
					atribute += "REAL\n";
				}
				
				addLine(atribute);
				var++;
				line = reader.readLine();				
			}
			
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		addLine("\n\n@data\n\n");		
	}
	
	public void addLine(String line) throws IOException {
		writer.write(line);
		line = "";
	}
	
	public File getFile() {
		return file;
	}
	
	public void saveToDisk() throws IOException {
		writer.close();
	}
}
